<?php


namespace app\api\controller\xiluhouse;


use app\common\controller\Api;
use app\common\model\xiluhouse\HouseBroker;
use app\common\model\xiluhouse\RentalCollection;
use app\common\model\xiluhouse\RentalOrderHouse;
use app\common\model\xiluhouse\RentalTag;
use app\common\model\xiluhouse\UserProfile;
use app\common\model\xiluhouse\Village;
use app\common\model\xiluhouse\VillageApply;
use app\common\model\xiluhouse\VillageBroker;
use app\common\validate\xiluhouse\RentalOrder;
use app\common\validate\xiluhouse\UserAuth;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Validate;
use function fast\array_get;

/**
 * 经纪人模块
 * @package app\api\controller\xiluhouse
 */
class Broker extends Api
{
    protected $noNeedRight = [ '*' ];

    protected $noBroker = [ 'apply' ];

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub

        $user_profile = UserProfile::where('user_id', $this->auth->id)->find();
        if (!$this->auth->match($this->noBroker) && $user_profile->is_broker < 1) {
            $this->error("非经纪人/房东不可访问");
        }
    }

    /**
     * 房东/经纪人申请
     */
    public function apply()
    {
        $params = $this->request->param('');
        if (!is_array($params)) {
            $this->error("非法参数");
        }
        $params['user_id'] = $this->auth->id;
        $params['is_broker'] = array_get($params, 'is_broker', 1);
        // $validate = new UserAuth();
        // if (!$validate->check($params)) {
        //     $this->error($validate->getError());
        // }
        $exist = \app\common\model\xiluhouse\UserAuth::where('user_id', $this->auth->id)
            ->where('is_broker', 1)
            ->whereIn('check_status', [ 0, 1 ])
            ->find();

        // if ($exist && $exist->check_status != 2) {
        //     $this->error("您已有申请记录");
        // }
        $params['check_status'] = 0;
        $params['refuse_reason'] = '';
        if ($exist) {
            $exist->allowField(true)->save($params);
        } else {
            $exist = \app\common\model\xiluhouse\UserAuth::create($params);
        }
        $this->success('申请成功，请等待审核', $exist);
    }


    /**
     * 我的房源管理
     */
    public function rental_lists()
    {
        $params = $this->request->param('');
        $status = array_get($params, 'status');
        $where['user_id'] = $this->auth->id;
        if (in_array($status, [ 'normal', 'hidden' ])) {
            $where['rental.status'] = $status;
        }
        if ($q = $this->request->param('q')) {
            $where['rental.name|village.name'] = [ 'like', "%$q%" ];
        }
        //日期条件
        if ($date = $this->request->param('date')) {
            $time1 = date('Y-m-01 00:00:00', strtotime($date));
            $time2 = date('Y-m-d 23:59:59', strtotime("$time1 +1 month -1 day"));
            $where['rental.createtime'] = [ 'between', [ strtotime($time1), strtotime($time2) ] ];
        }
        $lists = \app\common\model\xiluhouse\Rental::field("id,name,village_id,user_id,price,image,space,house_tag_ids,status,createtime,updatetime")->with([ 'village' => function ($query) {
            $query->withField('id,name,prov,city,region,street');
        } ])
            ->where($where)
            ->order('rental.updatetime', 'desc')
            ->paginate()
            ->each(function ($row) {
                //$row->append(['house_tag_ids_text_arr']);
                $row->house_tag_ids_text_arr = $row->rentalTags();
                $row->updatetime_text = date('m.d H:i', $row->updatetime);
                $row->createtime_date = date('m.d H:i', $row->createtime);
            });
        $this->success('查询成功', $lists);
    }

    /**
     * 上下架
     */
    public function multi_status()
    {
        $params = $this->request->param('');
        $rental_id = array_get($params, 'rental_id');
        $status = array_get($params, 'status');
        if (!$rental_id || !$status || !in_array($status, [ 'normal', 'hidden' ])) {
            $this->error('参数错误');
        }
        $where['user_id'] = $this->auth->id;
        $row = \app\common\model\xiluhouse\Rental::where('id', $rental_id)->where($where)->find();
        if (!$row) {
            $this->error('无权操作');
        }
        if (($status == 'hidden' && in_array($row->status, [ 'normal' ])) || ($status == 'normal' && in_array($row->status, [ 'hidden' ]))) {
            $row->status = $status;
            $row->allowField(true)->save();
        } else {
            $this->error('状态不可操作');
        }
        $this->success($status == 'normal' ? "上架成功" : '下架成功', $row);
    }

    public function multi_house_status()
    {
        $params = $this->request->param('');
        $rental_id = array_get($params, 'id');
        $status = array_get($params, 'status');
        if (!$rental_id || !$status || !in_array($status, [ 'normal', 'hidden' ])) {
            $this->error('参数错误');
        }
        $where['user_id'] = $this->auth->id;
        $row = \app\common\model\xiluhouse\House::where('id', $rental_id)->where($where)->find();
        if (!$row) {
            $this->error('无权操作');
        }
//        if (($status == 'hidden' && in_array($row->apply_status, [ 'normal' ])) || ($status == 'normal' && in_array($row->apply_status, [ 'hidden' ]))) {
            $row->apply_status = $status;
            $row->check_status = 0; // 编辑后需要重新审核
            $row->allowField(true)->save();
//        } else {
//            $this->error('状态不可操作');
//        }
        $this->success($status == 'normal' ? "已申请上架" : '已申请下架', $row);
    }


    /**
     * 代理房源管理
     */
    public function agent_rental_lists()
    {
        //$params = $this->request->param('');
//        $village_ids = VillageBroker::where('broker_user_id',$this->auth->id)->column('village_id')?:[];
//        if(!$village_ids){
//            $this->error('还未有代理小区呦~');
//        }
//        $where['village2.id'] = ['in',$village_ids];
        $where['rental.status'] = 'normal';
        $where['rental.is_public'] = '1';
        $where['rental.user_id'] = [ 'neq', $this->auth->id ];
        if ($q = $this->request->param('q')) {
            $where['rental.name|village2.name'] = [ 'like', "%$q%" ];
        }
        $lists = \app\common\model\xiluhouse\Rental::alias("rental")
            ->join('xiluhouse_village_broker village_broker', 'village_broker.village_id=rental.village_id')
            ->field("id,name,village_id,user_id,price,image,space,house_tag_ids,status,updatetime")
            ->with([ 'village2' => function ($query) {
                $query->withField('id,name,prov,city,region,street');
            } ])
            ->where('village_broker.broker_user_id', $this->auth->id)
            ->where($where)
            ->order('rental.updatetime', 'desc')
            ->paginate()
            ->each(function ($row) {
                //$row->append(['house_tag_ids_text_arr']);
                $row->house_tag_ids_text_arr = $row->rentalTags();
                $row->updatetime_text = date('m.d H:i', $row->updatetime);
            });
        $this->success('查询成功', $lists);
    }

    /**
     * 发起签约前获取房东信息
     */
    public function rental_lessor()
    {
        $params = $this->request->param('');
        if (!$rental_id = array_get($params, 'rental_id')) {
            $this->error('参数错误');
        }

        $rental = \app\common\model\xiluhouse\Rental::where('id', $rental_id)->find();
        if (!$rental) {
            $this->error('租房信息错误');
        }
        $user_auth = \app\common\model\xiluhouse\UserAuth::get([ 'user_id' => $rental->user_id ]);
        $this->success('获取成功', $user_auth ?? []);
    }

    /**
     * 发起签约
     * 谁发布的房源，谁就是房东
     */
    public function rental_sign()
    {
        $params = $this->request->param('');
        $validate = new RentalOrder();
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }
        $params['user_id'] = $this->auth->id;
//        if($params['lessor_mobile'] && $lessor_user = \app\common\model\xiluhouse\User::field('id,nickname,mobile')->where('mobile',$params['lessor_mobile'])->find()){
//            $this->error('房东手机号未注册');
//        }

        if ($params['renter_mobile'] && !$rental_user = \app\common\model\xiluhouse\User::field('id,nickname,mobile')->where('mobile', $params['renter_mobile'])->find()) {
            $this->error('租客手机号未注册');
        }
        $params['renter_user_id'] = isset($rental_user) ? $rental_user['id'] : 0;
        $params['renter_pay_money'] = bcadd(bcadd($params['deposit'], $params['renter_money'], 2), $params['renter_medium_money'], 2);
        $params['lessor_pay_money'] = $params['lessor_medium_money'];

        $rental = \app\common\model\xiluhouse\Rental::field("id,name,village_id,user_id,price,image,images,room_num,ting_num,wei_num,space,face,floor_num,content,building_descript,cosult_tel,house_type_id,house_tag_ids,status,updatetime")->with([ 'village2' => function ($query) {
            $query->withField('id,name,prov,city,region,street,addr,lat,lng');
        } ])
            ->where('rental.id', $params['rental_id'])
            ->order('rental.updatetime', 'desc')
            ->find();
        if (!$rental || $rental->status == 'hidden') {
            $this->error('当前房源不存在已下架');
        }
        //$rental->append(['house_tag_ids_text_arr']);
        $params['order_type'] = $rental->user_id == $this->auth->id ? 'direct' : 'agent';
        $params['platform'] = 'wxmini';
        $params['order_no'] = "S" . date('YmdHis') . mt_rand(100, 99999);
        $params['rent_start_date'] = strtotime($params['rent_start_date']);
        $params['rent_end_date'] = strtotime($params['rent_end_date']);
        $params['order_state'] = 1;
        $params['state'] = 1;
        $params['pay_status'] = 0;
        $params['lessor_state'] = 0;
        $params['lessor_user_id'] = $rental->user_id;
        $rental_order = new \app\common\model\xiluhouse\RentalOrder();
        $tags = $rental->rentalTags();
        $rentalTags = [];
        foreach ($tags as $tag) {
            if (isset($tag['tag']['name'])) {
                $rentalTags[] = $tag['tag']['name'];
            }
        }
        unset($tag);
        $building_descript = $rental->rentalTags(2);
        $descript = [];
        foreach ($building_descript as $v) {
            if (isset($v['type_tag']['name']) && isset($v['tag']['name'])) {
                $descript[] = [ $v['type_tag']['name'] => $v['tag']['name'] ];
            }
        }
        Db::startTrans();
        try {
            $rental_order->allowField(true)->save($params);
            #房子基本资料
            RentalOrderHouse::create([
                'order_id'          => $rental_order->id,
                'rental_id'         => $rental->id,
                'name'              => $rental->name,
                'village_id'        => $rental->village_id,
                'user_id'           => $rental->user_id,
                'price'             => $rental->price,
                'image'             => $rental->image,
                'images'            => $rental->images,
                'village_name'      => $rental->village2->name,
                'prov'              => $rental->village2->prov,
                'city'              => $rental->village2->city,
                'region'            => $rental->village2->region,
                'street'            => $rental->village2->street,
                'addr'              => $rental->village2->addr,
                'lat'               => $rental->village2->lat,
                'lng'               => $rental->village2->lng,
                'room_num'          => $rental->room_num,
                'ting_num'          => $rental->ting_num,
                'wei_num'           => $rental->wei_num,
                'space'             => $rental->space,
                'face'              => $rental->face,
                'floor_num'         => $rental->floor_num,
                'house_type_text'   => $rental->housetype ? $rental->housetype->name : '',
                'house_tag_text'    => $rentalTags ? implode(',', $rentalTags) : '',
                'content'           => $rental->content,
                'building_descript' => $descript ? json_encode(',', $descript) : '',
                'cosult_tel'        => $rental->cosult_tel,
            ]);

        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success('发起签约成功', $rental_order);
    }

    /**
     * 发起的签约列表
     */
    public function sign_lists()
    {
        $state = $this->request->param('state', -1);

        $query = \app\common\model\xiluhouse\RentalOrder::with([ 'rental', 'rentalUser' => function ($query) {
            $query->withField([ 'id', 'nickname', 'avatar' ]);
        }, 'lessorUser'                                                                 => function ($query) {
            $query->withField([ 'id', 'nickname', 'avatar' ]);
        } ])
            ->where('rental_order.user_id|rental_order.lessor_user_id', $this->auth->id);

        if ($q = $this->request->param('q')) {
            $query->where('rental_order.lessor_name|rental_order.lessor_mobile|rental_order.renter_name|rental_order.renter_mobile|rental.name', 'like', "%{$q}%");
        }

        switch ($state) {
            case -1:
                #已取消
                $query->where('order_state', 2);
                break;
            case 1:
                #待签约-两方都未签约
                $query->where('order_state', 1)
                    ->where('state', 1)
                    ->where('lessor_state', 0);
                break;
            case 2:
                #签约中-有一方未签约
                $query->where('order_state', 1)
                    ->where(function ($query) {
                        $query->where('state = 2 AND lessor_state = 0')->whereOr('state=1 AND lessor_state=1');
                    });
                break;
            case 3:
                #待支付-租客和房东都签约,但是租客未支付
                $query->where('order_state', 1)
                    ->where("state", 2)
                    ->where('lessor_state', 1)
                    ->where('pay_status', 0);
                break;
            case 4:
                #已完成-已签约-租客已支付
                $query->where('order_state', 3)
                    ->where('state', 2)
                    ->where('lessor_state', 1)
                    ->where('pay_status', 1);
                break;
        }
        $user_id = $this->auth->id;
        $lists = $query->order('updatetime', 'desc')
            ->paginate()
            ->each(function ($row) use ($user_id) {
                $row->rental->append([ 'house_tag_text_arr' ]);
                $row->is_lessor = $user_id == $row->lessor_user_id ? 1 : 0;
            });

        $this->success('查询成功', $lists);
    }

    /**
     * 经纪人/房东取消签约
     */
    public function cancel_sign()
    {
        $rental_order_id = $this->request->param('rental_order_id');
        if (!$rental_order_id) {
            $this->error('参数错误');
        }
        $rental_order = \app\common\model\xiluhouse\RentalOrder::where('id', $rental_order_id)->find();
        if (!$rental_order) {
            $this->error('当前订单不存在');
        }
        if (!in_array($rental_order->checkinfo, [ 0, 1, 2, 3 ])) {
            $this->error('当前状态不可取消');
        }
        if ($rental_order->user_id != $this->auth->id && $this->auth->id != $rental_order->lessor_user_id) {
            $this->error('没有权限');
        }
        $rental_order->order_state = '2';

        if ($this->auth->id == $rental_order->lessor_user_id) {
            //房东取消
            $rental_order->lessor_state = -1;
        }

        $rental_order->canceltime = time();
        $rental_order->save();
        $this->success('签约取消成功');
    }

    /**
     * 代理小区
     */
    public function my_village()
    {
        $lists = VillageBroker::with([ 'village' => function ($query) {
            $query->where('status', 'normal')->withField([ 'id', 'name', 'prov', 'city', 'region', 'street', 'addr' ]);
        } ])
            ->where('broker_user_id', $this->auth->id)
            ->order('id', 'desc')
            ->paginate();
        $this->success('查询成功', $lists);
    }

    /**
     * 小区申请
     */
    public function apply_village()
    {
        $params = $this->request->param('');
        if (!$village_id = array_get($params, 'village_id')) {
            $this->error('小区参数错误');
        }
//        $village = Village::get($village_id);
//        if(!$village || $village->status == 'hidden'){
//            $this->error('小区不存在或已下架');
//        }
        $exist = VillageBroker::where('broker_user_id', $this->auth->id)
            ->whereIn('village_id', $village_id)
            ->find();
        if ($exist) {
            $this->error('您已拥有该小区');
        }
//        $village_apply = VillageApply::where('broker_user_id',$this->auth->id)
//            ->where('village_id',$village_id)
//            ->where('check_status','0')
//            ->find();
//        if($village_apply){
//            $this->error('您申请的小区正在审核中');
//        }
        $row = VillageApply::create([
            'broker_user_id' => $this->auth->id,
            'village_id'     => $village_id
        ]);
        $this->success('申请成功', $row);
    }

    /**
     * 添加小区
     */
    public function add_village()
    {
        $params = $this->request->param('');
        $params['user_id'] = $this->auth->id;
        $validate = new Validate([
            'name|小区名称'    => 'require',
            'user_id|发布用户' => 'require',
            'prov|省份'        => 'require',
            'city|市区'        => 'require',
            'region|区/县'     => 'require',
            'street|街道'      => 'require',
            'addr|详细地址'    => 'require',
            'images|小区图片'  => 'require'
        ]);
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }
        $model = new \app\common\model\xiluhouse\Village();
        if ($model->where('name', $params['name'])->where('prov', $params['prov'])->where('city', $params['city'])->find()) {
            $this->error('当前小区已存在');
        }
        $params['image'] = !empty($params['image']) ? $params['image'] : explode(',', $params['images'])[0];

        $address = $params['prov'] . $params['city'] . $params['region'] . $params['street'] . $params['addr'];
        $result = getGeo($address);
        if ($result['status'] == 0) {
            // $this->error('获取经纬度失败，请选择正确的地址');
        }
        $params['lat'] = $result['lat'] ?? 0;
        $params['lng'] = $result['lng'] ?? 0;
        $params['check_status'] = 0;

        Db::startTrans();
        try {
            $ret = $model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success('添加成功', $ret);
    }

    /**
     * 移除小区
     */
    public function remove_village()
    {
        $village_broker_id = $this->request->post('village_broker_id');
        if (!$village_broker_id) {
            $this->error('参数错误');
        }
        $row = VillageBroker::where('id', $village_broker_id)
            ->where('broker_user_id', $this->auth->id)
            ->order('id', 'desc')
            ->find();
        if (!$row) {
            $this->error('小区已不存在');
        }
        $row->delete();
        $this->success('移除成功');
    }

    /**
     * 添加房源
     */
    public function add_rental()
    {
        $params = $this->request->only([ "id", "image", "village_id", "name", "house_type_id", "rental_mode_id", "images", "is_public", "fixturestime", "buildingtime", "price", "space", "face", "floor_num", "ting_num", "room_num", "wei_num", "content", 'tag', 'status', 'ladder', 'village', 'room_number' ]);
        //halt($params);
        $params['user_id'] = $this->auth->id;
        $validate = new Validate([
            // 'name|租房名称'            => 'require',
            // 'village_id|所属小区'      => 'require|gt:0',
            // 'user_id|发布用户'         => 'require',
            // 'price|价格'              => 'gt:0',
            // 'images|图片'             => 'require',
            // 'space|面积'              => 'require',
            // 'face|朝向'               => 'require',
            // 'buildingtime|建造时间'    => 'require',
            // 'fixturestime|装修时间'    => 'require',
            // 'house_type_id|房源类型'   => 'require',
            // 'rental_mode_id|租赁模式'  => 'require',
            // 'content|详情描述'         => 'require',
            //'building_descript|建筑信息'=> 'require',
        ]);
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }
        // $village = Village::get($params['village_id']);
        // if (!$village || $village->check_status !== 1) {
        //     $this->error("小区还在审核中");
        // }
        // if (!$village || $village->status == 'hidden') {
        //     $this->error("小区已下架");
        // }
        $params['image'] = !empty($params['image']) ? $params['image'] : explode(',', $params['images'])[0];
        //$params['building_descript'] = json_encode($params['building_descript']);
        $house_tag_ids = [];
        $house_tag_type_ids = [];
        foreach ($params['tag'] as $tag) {
            $house_tag_ids[] = $tag['tag_id'];
            if (isset($house_tag_type_ids[$tag['tag_type_id']])) {
                $house_tag_type_ids[$tag['tag_type_id']] .= ',' . $tag['tag_id'];
            } else {
                $house_tag_type_ids[$tag['tag_type_id']] = $tag['tag_id'];
            }
        }
        unset($tag);
        //halt($house_tag_type_ids);
        $params['house_tag_ids'] = implode(',', $house_tag_ids);
        $model = new \app\common\model\xiluhouse\Rental();
        Db::startTrans();
        try {
            if ($rental_id = array_get($params, 'id')) {
                unset($params['id']);
                $row = $model->get($rental_id);
                $ret = $row->allowField(true)->save($params);
                $result2 = RentalTag::setTagIds($row, $house_tag_type_ids, 'edit');
            } else {
                $ret = $model->allowField(true)->save($params);
                $result2 = RentalTag::setTagIds($model, $house_tag_type_ids);
                $row = $model;
            }
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success('保存成功', $row);
    }


    /**
     * 添加楼栋
     */
    public function add_house()
    {
        $params = $this->request->only([ "name", "sale_state", "is_low_price_protect",
            "price", "min_total_price", "max_total_price", "image", "vr_url", "build_image", "images",
            "prov", "city", "region", "street", "addr", "subway_distance",
            "subway_distance_text", "house_type_id", "house_developer_id",
            "room_num", "floor_num", "elevator_num", "stepLadder_num", "user_id",
            "house_tag_ids", "min_room_num", "max_room_num", "min_space",
            "max_space", "build_space", "opentime", "deliverytime", "content",
            "cosult_tel", "discounts", "first_price_msg", "hot_msg",
            'nearby_bus_json', 'nearby_subway_json', 'nearby_school_json',
            'nearby_shop_json', 'nearby_hospital_json', 'alias_name']);

        $params['user_id'] = $this->auth->id;
        $validate = new Validate([
            'name|楼盘名称' => 'require',
            'price|价格'    => 'gt:0',
            'images|多图'   => 'require',
            'prov|省'       => 'require',
            'city|市'       => 'require',
            'region|区'     => 'require',
            'street|街道'   => 'require',
            'addr|地址'     => 'require',
        ]);
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }
        $params['images'] = explode(',', $params['images']);
        $params['image'] = !empty($params['image']) ? $params['image'] : $params['images'][0];
        $address = $params['prov'] . $params['city'] . $params['region'] . $params['street'] . $params['addr'];
        $result = getGeo($address);
        if ($result['status'] == 0) {
            $this->error('获取经纬度失败，请选择正确的地址');
        }
        $params['lat'] = $result['lat'];
        $params['lng'] = $result['lng'];
        $img = [];
        foreach ($params['images'] as $row) {
            $img[] = [ 'images' => $row ];
        }
        $params['images'] = json_encode($img);


        // 处理周边地址
        $params['nearby_bus_num'] = 0;
        if ($params['nearby_bus_json']) {
            $arr = json_decode($params['nearby_bus_json'], true);
            foreach ($arr as $key => $value) {
                if ($value['lat']) {
                    $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $value['lat'], $value['lng']) . 'm';
                } else {
                    $now_address = $params['prov'] . $params['city'] . $params['region'] . $params['street'] . $value['name'];
                    $addr_res = getGeo($now_address);
                    if ($addr_res['status'] == 0) {
                        $this->error('获取公交' . ($key + 1) . '经纬度失败，请选择正确的地址');
                    }
                    $arr[$key]['lat'] = $addr_res['lat'];
                    $arr[$key]['lng'] = $addr_res['lng'];
                    $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $arr[$key]['lat'], $arr[$key]['lng']) . 'm';
                }
            }
            $params['nearby_bus_num'] = count($arr);
            $params['nearby_bus_json'] = json_encode($arr);
        }
        $params['nearby_subway_num'] = 0;
        if ($params['nearby_subway_json']) {
            $arr = json_decode($params['nearby_subway_json'], true);
            foreach ($arr as $key => $value) {
                if ($value['lat']) {
                    $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $value['lat'], $value['lng']) . 'm';
                } else {
                    $now_address = $params['prov'] . $params['city'] . $params['region'] . $params['street'] . $value['name'];
                    $addr_res = getGeo($now_address);
                    if ($addr_res['status'] == 0) {
                        $this->error('获取地铁' . ($key + 1) . '经纬度失败，请选择正确的地址');
                    }
                    $arr[$key]['lat'] = $addr_res['lat'];
                    $arr[$key]['lng'] = $addr_res['lng'];
                    $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $arr[$key]['lat'], $arr[$key]['lng']) . 'm';
                }
            }
            $params['nearby_subway_num'] = count($arr);
            $params['nearby_subway_json'] = json_encode($arr);
        }
        $params['nearby_school_num'] = 0;
        if ($params['nearby_school_json']) {
            $arr = json_decode($params['nearby_school_json'], true);
            foreach ($arr as $key => $value) {
                if ($value['lat']) {
                    $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $value['lat'], $value['lng']) . 'm';
                } else {
                    $now_address = $params['prov'] . $params['city'] . $params['region'] . $params['street'] . $value['name'];
                    $addr_res = getGeo($now_address);
                    if ($addr_res['status'] == 0) {
                        $this->error('获取学校' . ($key + 1) . '经纬度失败，请选择正确的地址');
                    }
                    $arr[$key]['lat'] = $addr_res['lat'];
                    $arr[$key]['lng'] = $addr_res['lng'];
                    $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $arr[$key]['lat'], $arr[$key]['lng']) . 'm';
                }
            }
            $params['nearby_school_num'] = count($arr);
            $params['nearby_school_json'] = json_encode($arr);
        }
        $params['nearby_shop_num'] = 0;
        if ($params['nearby_shop_json']) {
            $arr = json_decode($params['nearby_shop_json'], true);
            foreach ($arr as $key => $value) {
                if ($value['lat']) {
                    $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $value['lat'], $value['lng']) . 'm';
                } else {
                    $now_address = $params['prov'] . $params['city'] . $params['region'] . $params['street'] . $value['name'];
                    $addr_res = getGeo($now_address);
                    if ($addr_res['status'] == 0) {
                        $this->error('获取购物' . ($key + 1) . '经纬度失败，请选择正确的地址');
                    }
                    $arr[$key]['lat'] = $addr_res['lat'];
                    $arr[$key]['lng'] = $addr_res['lng'];
                    $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $arr[$key]['lat'], $arr[$key]['lng']) . 'm';
                }
            }
            $params['nearby_shop_num'] = count($arr);
            $params['nearby_shop_json'] = json_encode($arr);
        }
        $params['nearby_hospital_num'] = 0;
        if ($params['nearby_hospital_json']) {
            $arr = json_decode($params['nearby_hospital_json'], true);
            foreach ($arr as $key => $value) {
                if ($value['lat']) {
                    $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $value['lat'], $value['lng']) . 'm';
                } else {
                    $now_address = $params['prov'] . $params['city'] . $params['region'] . $params['street'] . $value['name'];
                    $addr_res = getGeo($now_address);
                    if ($addr_res['status'] == 0) {
                        $this->error('获取医疗' . ($key + 1) . '经纬度失败，请选择正确的地址');
                    }
                    $arr[$key]['lat'] = $addr_res['lat'];
                    $arr[$key]['lng'] = $addr_res['lng'];
                    $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $arr[$key]['lat'], $arr[$key]['lng']) . 'm';
                }
            }
            $params['nearby_hospital_num'] = count($arr);
            $params['nearby_hospital_json'] = json_encode($arr);
        }

        $params['status'] = 'hidden';
        $model = new \app\common\model\xiluhouse\House();
        Db::startTrans();
        try {
            $model->allowField(true)->save($params);
            HouseBroker::create(
                [
                    'user_id'  => $params['user_id'],
                    'house_id' => $model->id,
                ]
            );
            // $row = $model;
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success('保存成功');
    }

    /**
     * @title   房源详情
     * @desc    房源详情
     * @param int $id 0   房源id
     */
    // public function rental_detail()
    // {
    //     $rental_id = $this->request->param('rental_id/d', 0);
    //     if (!$rental_id) {
    //         $this->error('参数错误');
    //     }
    //     $info = \app\common\model\xiluhouse\Rental::with([ 'village2' => function ($query) {
    //         $query->withField([ 'id', 'name', 'prov', 'city', 'region', 'street', 'addr' ]);
    //     } ])
    //         ->field('rental.id,image,images,village_id,rental.name,house_type_id,is_public,fixturestime,buildingtime,price,space,face,floor_num,ting_num,room_num,wei_num,content')
    //         ->where('rental.id', $rental_id)
    //         ->find();
    //     if (!$info) {
    //         $this->error('查询不到该房源');
    //     }
    //     $info->append([ 'images_arr' ]);
    //     $this->success('', $info);
    // }

    public function rental_detail()
    {
        $rental_id = $this->request->param('rental_id/d', 0);
        if (!$rental_id) {
            $this->error('参数错误');
        }
        $info = \app\common\model\xiluhouse\Rental::field('id,image,images,village,room_number,name,house_type_id,is_public,fixturestime,buildingtime,price,space,face,floor_num,ting_num,room_num,wei_num,content')
            ->where('id', $rental_id)
            ->find();
        if (!$info) {
            $this->error('查询不到该房源');
        }
        $info->append([ 'images_arr' ]);
        $this->success('', $info);
    }


    public function house_info()
    {
        $id = $this->request->param('id/d', 0);
        if (!$id) {
            $this->error('参数错误');
        }
        $info = \app\common\model\xiluhouse\House::where('id', $id)
            ->find();
        if (!$info) {
            $this->error('查询不到该房源');
        }
        if ($info['images']) {
            $info['images'] = array_column(json_decode($info['images'], true), 'images');
                 foreach ($info['images']??[] as $k=>$row){
            $arr[$k] = cdnurl($row);
        }
        $info->setAttr('images',$arr);

        }
        $keys = [ 'shop', 'subway', 'bus', 'hospital', 'school' ];
        foreach ($keys as $key) {
            $keyNum = "nearby_{$key}_num";
            if (!$info[$keyNum]) {
                continue;
            }
            $keyJson = "nearby_{$key}_json";
            $info->setAttr($keyJson,json_decode($info[$keyJson], true));
            // $info[$keyJson] = json_decode($info[$keyJson], true);


        }

        $info->setAttr('build_image',cdnurl($info['build_image']));
          $info->setAttr('image',cdnurl($info['image']));
        // $info['build_image'] = cdnurl($info['build_image']);
        // $info['image'] = cdnurl($info['image']);
        //



//        $info['opentime'] = date("Y-m-d", $info['opentime']);
//        $info['deliverytime'] = date("Y-m-d", $info['deliverytime']);


        $this->success('', $info);
    }


    /**
     * 角标
     */
    public function state_bubble()
    {

        #已取消
        $cancel_count = \app\common\model\xiluhouse\RentalOrder::with([ 'rental' ])
            ->where('rental_order.user_id|rental_order.lessor_user_id', $this->auth->id)->where('order_state', 2)->count('rental_order.id');
        #待签约-两方都未签约
        $unsign_count = \app\common\model\xiluhouse\RentalOrder::with([ 'rental' ])
            ->where('rental_order.user_id|rental_order.lessor_user_id', $this->auth->id)
            ->where('order_state', 1)
            ->where('state', 1)
            ->where('lessor_state', 0)
            ->count('rental_order.id');
        #签约中-有一方未签约
        $signing_count = \app\common\model\xiluhouse\RentalOrder::with([ 'rental' ])
            ->where('rental_order.user_id|rental_order.lessor_user_id', $this->auth->id)
            ->where('order_state', 1)
            ->where(function ($query) {
                $query->where('state = 2 AND lessor_state = 0')->whereOr('state=1 AND lessor_state=1');
            })->count('rental_order.id');
        #待支付-租客和房东都签约,但是租客未支付
        $unpaid_count = \app\common\model\xiluhouse\RentalOrder::with([ 'rental' ])
            ->where('rental_order.user_id|rental_order.lessor_user_id', $this->auth->id)
            ->where('order_state', 1)
            ->where("state", 2)
            ->where('lessor_state', 1)
            ->where('pay_status', 0)
            ->count('rental_order.id');
        #已完成-已签约-租客已支付
        $sign_finish_count = \app\common\model\xiluhouse\RentalOrder::with([ 'rental' ])
            ->where('rental_order.user_id|rental_order.lessor_user_id', $this->auth->id)
            ->where('order_state', 3)
            ->where('state', 2)
            ->where('lessor_state', 1)
            ->where('pay_status', 1)
            ->count('rental_order.id');
        $this->success('查询成功', [
            'cancel_count'      => $cancel_count,
            'unsign_count'      => $unsign_count,
            'signing_count'     => $signing_count,
            'unpaid_count'      => $unpaid_count,
            'sign_finish_count' => $sign_finish_count,
        ]);
    }
}
